package com.leetcode;

/**
 * TODO
 *
 * @author lefly
 * @version 1.0
 * @classname No169
 * @description
 * @date 2021/1/28 下午1:51
 */
public class No169 {
    public static void main(String[] args) {
        int[] nums = {2,2,1,1,1,2,2};
        int res = majorityElement(nums);
        System.out.println(res);
    }

    public static int majorityElement(int[] nums) {
        if (nums == null || nums.length < 1) {
            return 0;
        }
        int len = nums.length;
        int majorityNum = nums[0];
        int count = 1;
        if (len == 1) {
            return majorityNum;
        }
        for (int i = 1; i < len; i++) {
            if (nums[i] == majorityNum) {
                count++;
            } else {
                count--;

            }
            if (count == 0) {
                majorityNum = nums[i];
                count = 1;
            }
        }
        count = 0;
        for (int n : nums) {
            if (n == majorityNum) {
                count++;
            }
        }
        if (count >= len / 2) {
            return majorityNum;
        }
        return 0;

    }

}
